<template>
        <div class="filter-row">
          <label>发布时间</label>
          <div style="display:flex;gap:6px;align-items:center;">
            <input v-model="filterStartTime" type="date" placeholder="开始日期" style="width:120px;" />
            <span>-</span>
            <input v-model="filterEndTime" type="date" placeholder="结束日期" style="width:120px;" />
          </div>
        </div>
  <Navbar />
  <div class="product-page-layout">
    <aside class="product-sidebar">
      <h3>筛选条件</h3>
      <form class="filter-form" @submit.prevent="applyFilter">
        <div class="filter-row">
          <label>关键字</label>
          <input v-model="filterKeyword" placeholder="商品名/描述" />
        </div>
        <div class="filter-row">
          <label>分类</label>
          <select v-model="filterCategory">
            <option value="">不限</option>
            <option v-for="cat in allCategories" :key="cat.category_id" :value="cat.category_id">{{ cat.name }}</option>
          </select>
        </div>
        <div class="filter-row">
          <label>商品状态</label>
          <select v-model="filterCondition">
            <option value="">不限</option>
            <option value="0">审核中</option>
            <option value="1">在售</option>
            <option value="2">已售</option>
            <option value="3">下架</option>
          </select>
        </div>
        <div class="filter-row">
          <label>价格排序</label>
          <select v-model="filterPriceOrder">
            <option value="">默认</option>
            <option value="asc">价格从低到高</option>
            <option value="desc">价格从高到低</option>
          </select>
        </div>
        <div class="filter-row">
          <label>价格区间</label>
          <div style="display:flex;gap:6px;align-items:center;">
            <input v-model="filterMinPrice" type="number" min="0" placeholder="最低价" style="width:60px;" />
            <span>-</span>
            <input v-model="filterMaxPrice" type="number" min="0" placeholder="最高价" style="width:60px;" />
          </div>
        </div>
        <button class="filter-btn" type="submit">筛选</button>
      </form>
    </aside>
    <main class="product-main">
      <div class="main-header">
        <h1>商品信息</h1>
        <button class="add-btn" @click="() => { cancelForm(); showForm = true; }">发布商品</button>
      </div>
      <!-- 模态框背景遮罩 -->
      <div v-if="showForm" class="modal-overlay" @click="cancelForm"></div>
      
      <!-- 模态框内容 -->
      <div v-if="showForm" class="modal-content">
        <div class="modal-header">
          <h2>{{ editingProductId ? '编辑商品' : '发布新商品' }}</h2>
          <button class="close-btn" @click="cancelForm">&times;</button>
        </div>
        <div class="modal-body">
          <form class="product-form">
            <div class="form-row">
              <label>商品名称</label>
              <input v-model="title" required placeholder="请输入商品名称" />
            </div>
            <div class="form-row">
              <label>商品描述</label>
              <textarea v-model="description" required placeholder="请输入商品描述"></textarea>
            </div>
            <div class="form-row">
              <label>售价</label>
              <input v-model="price" type="number" min="0" required placeholder="请输入售价" />
            </div>
            <div class="form-row">
              <label>原价</label>
              <input v-model="originalPrice" type="number" min="0" placeholder="请输入原价（可选）" />
            </div>
            <div class="form-row">
              <label>分类</label>
              <select v-model="category" required>
                <option value="">请选择分类</option>
                <option v-for="cat in allCategories" :key="cat.category_id" :value="cat.category_id">{{ cat.name }}</option>
              </select>
            </div>
            <div class="form-row">
              <label>商品图片</label>
              <input type="file" @change="onImageChange" accept="image/*" multiple />
              <div class="image-previews">
                <div v-for="(url, index) in imageUrls" :key="index" class="preview-container">
                  <img :src="url" class="image-preview" alt="图片预览" />
                  <button @click.stop="removeImage(index)" class="remove-image-btn">×</button>
                </div>
              </div>
            </div>
            <button class="submit-btn" type="submit" @click.prevent="submitProduct">{{ editingProductId ? '更新' : '发布' }}</button>
            <button class="cancel-btn" type="button" @click="cancelForm">取消</button>
            <span v-if="msg" class="msg">{{ msg }}</span>
          </form>
        </div>
      </div>
      <div v-else>        <div v-if="loading">加载中...</div>        <div v-else-if="products.length === 0">暂未发布商品</div>        <div v-else>          <div class="my-products-list">            <div v-for="item in products" :key="item.product_id" class="my-product-item">              <img :src="getProductImageUrl(item.image_url)" class="my-product-img" alt="商品图片" />              <div class="my-product-info">                <div class="my-product-title">{{ item.title }}</div>                <div class="my-product-desc">{{ item.description.substring(0, 30) }}{{ item.description.length > 30 ? '...' : '' }}</div>                <div class="my-product-meta">                  <div class="my-product-price">¥{{ item.price }}</div>                  <div>{{ getCategoryName(item.category_id) }}</div>                  <div>                    <span v-if="item.status === 0" class="status-tag status-pending">审核中</span>                    <span v-if="item.status === 1" class="status-tag status-active">在售</span>                    <span v-if="item.status === 2" class="status-tag status-sold">已售</span>                    <span v-if="item.status === 3" class="status-tag status-offline">下架</span>                  </div>                </div>              </div>              <div class="my-product-actions">                <button class="btn-编辑" @click="editProduct(item.product_id)">编辑</button>                <button v-if="item.status !== 3" class="btn-删除" @click="deleteProduct(item.product_id)">下架</button>                <button v-if="item.status === 3" class="btn-上架" @click="upProduct(item.product_id)">上架</button>              </div>
          </div>
          
          <!-- 分页组件 -->
          <div class="pagination-container">
            <div class="pagination-info">
              共 {{totalPages}} 页，当前第 {{currentPage}} 页，每页 {{pageSize}} 条
            </div>
            <div class="pagination-buttons">
              <button @click="prevPage" :disabled="currentPage === 1" class="pagination-btn">上一页</button>
              <button
                v-for="page in pageRange"
                :key="page"
                @click="goToPage(page)"
                :class="{ 'pagination-btn': true, 'active': page === currentPage }"
              >
                {{ page }}
              </button>
              <button @click="nextPage" :disabled="currentPage === totalPages" class="pagination-btn">下一页</button>
            </div>
          </div>
        </div>      </div>      </div>
    </main>
  </div>
</template>

<script setup lang="ts">
const filterStartTime = ref('');
const filterEndTime = ref('');
const filterCondition = ref('');
const filterPriceOrder = ref('');
import { ref, onMounted, computed } from 'vue';
import axios from 'axios';
import Navbar from '../components/Navbar.vue';

// 添加API基础路径和商品图片URL处理函数
const API_BASE = import.meta.env.VITE_API_BASE_URL || 'http://localhost:5000';

// 拼接完整商品图片地址
const getProductImageUrl = (imageUrl: string) => {
  if (!imageUrl) return defaultProductImg;
  if (imageUrl.startsWith('http') || imageUrl.startsWith('data:')) return imageUrl;
  if (imageUrl.startsWith('/uploads/')) return API_BASE + imageUrl;
  return defaultProductImg;
};

const showForm = ref(false);
const loading = ref(false);
const products = ref<any[]>([]);
const defaultProductImg = '/src/assets/product.svg';

// 筛选相关
const allCategories = ref<any[]>([]);
const filterCategory = ref('');
const filterKeyword = ref('');
const filterMinPrice = ref('');
const filterMaxPrice = ref('');

// 分页相关状态
const currentPage = ref(1);
const totalPages = ref(1);
const pageSize = ref(10); // 每页显示10条数据

const title = ref('');
const description = ref('');
const price = ref('');
const originalPrice = ref('');
const category = ref('');
// 定义扩展File类型的接口
interface ExtendedFile extends File {
  isOriginal?: boolean;
  originalUrl?: string;
}

const imageFiles = ref<ExtendedFile[]>([]);
const imageUrls = ref<string[]>([]);
const msg = ref('');// 编辑商品相关状态
const editingProductId = ref<number|null>(null); // 添加编辑中的商品ID
const originalImageUrls = ref<string[]>([]); // 存储原始图片URL，用于比较删除操作

const fetchCategories = async () => {
  try {
    const res = await axios.get('/api/product/categories');
    // 直接使用扁平结构的分类数据
    allCategories.value = res.data.categories || [];
  } catch {}
};

const fetchProducts = async () => {
  loading.value = true;
  try {
    const token = localStorage.getItem('token');
    console.log(`[${new Date().toLocaleString()}] [INFO] 获取商品列表请求`);
    const res = await axios.get('/api/product/my', {
      headers: token ? { Authorization: `Bearer ${token}` } : {}
    });
    products.value = res.data.products || [];
    console.log(`[${new Date().toLocaleString()}] [INFO] 获取商品列表成功: 数量=${products.value.length}`);
  } catch (err) {
    console.error(`[${new Date().toLocaleString()}] [ERROR] 获取商品列表失败: ${err}`);
    products.value = [];
  }
  loading.value = false;
};

onMounted(() => {
  fetchCategories();
  fetchProducts();
});

// 处理图片上传，并限制最多上传10张
  const onImageChange = (e: Event) => {
    const files = (e.target as HTMLInputElement).files;
    if (files) {
      // 计算还能上传多少张图片
      const remainingSlots = 10 - imageFiles.value.length;
      if (remainingSlots <= 0) {
        console.warn(`[${new Date().toISOString()}] [WARN] [文件上传] 已达到最大上传数量(10张)`);
        msg.value = '最多只能上传10张图片';
        return;
      }
      
      // 只取剩余数量的文件
      const filesToUpload = Array.from(files).slice(0, remainingSlots);
      
      for (let i = 0; i < filesToUpload.length; i++) {
        const file = filesToUpload[i];
        imageFiles.value.push(file);
        imageUrls.value.push(URL.createObjectURL(file));
        console.log(`[${new Date().toISOString()}] [DEBUG] [文件上传] 已添加新图片 ${imageFiles.value.length}/10: ${file.name}`);
      }
    }
  };

const removeImage = (index: number) => {
  imageFiles.value.splice(index, 1);
  imageUrls.value.splice(index, 1);
};

const submitProduct = async () => {
  msg.value = '';
  // 处理输入字段前后空格
  const trimmedTitle = title.value.trim();
  const trimmedDescription = description.value.trim();

  // 验证所有必填字段
  if (!trimmedTitle || !trimmedDescription || !price.value || !category.value) {
    msg.value = '请填写完整信息';
    if(!trimmedTitle) console.log(`[${new Date().toLocaleString()}] [INFO] 商品名称不能为空`);
    if(!trimmedDescription) console.log(`[${new Date().toLocaleString()}] [INFO] 商品描述不能为空`);
    if(!price.value) console.log(`[${new Date().toLocaleString()}] [INFO] 售价不能为空`);
    if(!category.value) console.log(`[${new Date().toLocaleString()}] [INFO] 分类不能为空`);
    return;
  }

  // 验证价格是否为有效数字
  if ( Number(price.value) <= 0 || (originalPrice.value && Number(originalPrice.value) <= 0) ) {
    msg.value = '请输入有效的售价';
    return;
  }

  try {
    const token = localStorage.getItem('token');
    const formData = new FormData();
    formData.append('title', trimmedTitle);
    formData.append('description', trimmedDescription);
    formData.append('price', price.value);
    formData.append('original_price', originalPrice.value);
    formData.append('category_id', category.value);
    // 添加多张图片
      // 处理图片上传：区分原始图片和新上传图片
      // 筛选出用户新上传的图片（非原始图片）
      interface ExtendedFile extends File {
        isOriginal?: boolean;
        originalUrl?: string;
      }

      const newFiles = (imageFiles.value as ExtendedFile[]).filter(file => !file.isOriginal && file.size > 0);
      console.log(`[${new Date().toISOString()}] [INFO] [文件上传] 准备上传 ${newFiles.length} 张新图片`);
      newFiles.forEach((file, index) => {
        formData.append('images', file);
        console.log(`[${new Date().toISOString()}] [DEBUG] [文件上传] 已添加新图片 ${index + 1}/${newFiles.length}: ${file.name}`);
      });

    if (editingProductId.value) {
      // 更新商品
      console.log(`[${new Date().toLocaleString()}] [INFO] [更新商品] 准备更新商品，商品ID: ${editingProductId.value}`);

      // 处理删除的图片

      // 筛选出被删除的原始图片URL
      // 1. 获取所有原始图片的相对路径URL（从编辑开始时存储的）
      const allOriginalUrls = [...originalImageUrls.value];

      // 2. 获取当前保留的原始图片相对路径URL
      const currentOriginalUrls = (imageFiles.value as ExtendedFile[])
        .filter(file => file.isOriginal)
        .map(file => file.originalUrl || '');

      // 3. 找出被删除的原始图片URL（未被保留在currentOriginalUrls中的）
      const deletedOriginalUrls = allOriginalUrls
        .filter(url => !currentOriginalUrls.includes(url));

      console.log(`[${new Date().toLocaleString()}] [DEBUG] [删除图片] 所有原始图片: ${JSON.stringify(allOriginalUrls)}`);
      console.log(`[${new Date().toLocaleString()}] [DEBUG] [删除图片] 当前保留图片: ${JSON.stringify(currentOriginalUrls)}`);
      console.log(`[${new Date().toLocaleString()}] [DEBUG] [删除图片] 被删除图片: ${JSON.stringify(deletedOriginalUrls)}`);

      if (deletedOriginalUrls.length > 0) {
        formData.append('deleted_images', JSON.stringify(deletedOriginalUrls));
        console.log(`[${new Date().toLocaleString()}] [INFO] [更新商品] 已添加 ${deletedOriginalUrls.length} 张待删除图片`);
      }

      // 如果没有新图片且没有删除任何原始图片，添加标记
      const newFiles = (imageFiles.value as ExtendedFile[]).filter(file => !file.isOriginal);
      if (newFiles.length === 0 && deletedOriginalUrls.length === 0) {
        formData.append('no_new_images', 'true');
        console.log(`[${new Date().toLocaleString()}] [INFO] [更新商品] 没有新图片且没有删除图片，添加no_new_images标记`);
      }

      // 发送更新请求
      await axios.put(`/api/product/${editingProductId.value}`, formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
          ...(token ? { Authorization: `Bearer ${token}` } : {})
        }
      });
      console.log(`[${new Date().toLocaleString()}] [SUCCESS] [更新商品] 商品更新成功，商品ID: ${editingProductId.value}`);
      msg.value = '更新成功';
    } else {
      // 创建新商品
      await axios.post('/api/product/create', formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
          ...(token ? { Authorization: `Bearer ${token}` } : {})
        }
      });
      msg.value = '发布成功';
      console.log(`[${new Date().toLocaleString()}] [SUCCESS] [创建商品] 商品创建成功`);
    }

    showForm.value = false;
    applyFilter(); // 重新获取商品列表并保持筛选条件
    editingProductId.value = null; // 重置编辑状态
  } catch (err: any) {
    msg.value = err?.response?.data?.message || '操作失败';
    console.error(`[${new Date().toLocaleString()}] [ERROR] [${editingProductId.value ? '更新商品' : '创建商品'}] 操作失败，错误信息: ${err?.message || '未知错误'}`);
  }
};

const cancelForm = () => {
  showForm.value = false;
  title.value = '';
  description.value = '';
  price.value = '';
  originalPrice.value = ''; // 重置原价
  category.value = '';
  imageFiles.value = [];
  imageUrls.value = [];
  msg.value = '';
  editingProductId.value = null; // 重置编辑状态
};



// 上架商品
const upProduct = async (productId: number) => {
  const currentTime = new Date().toLocaleString();
  console.log(`[${currentTime}] [INFO] [上架商品] 开始上架商品，商品ID: ${productId}`);

  try {
    const token = localStorage.getItem('token');
    const response = await axios.put(`/api/product/${productId}/status`, 
      { status: 1 },
      {
        headers: {
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json'
        }
      }
    );

    console.log(`[${currentTime}] [SUCCESS] [上架商品] 商品上架成功，商品ID: ${productId}`);
    applyFilter(); // 重新获取商品列表并保持筛选条件
  } catch (error: unknown) {
    const errorMessage = error instanceof Error ? error.message : '未知错误';
    console.error(`[${currentTime}] [ERROR] [上架商品] 商品上架失败，错误信息: ${errorMessage}`);
  }
};

// 下架商品
const deleteProduct = async (productId: number) => {
  const currentTime = new Date().toLocaleString();
  console.log(`[${currentTime}] [INFO] [下架商品] 开始下架商品，商品ID: ${productId}`);

  try {
    const token = localStorage.getItem('token');
    const response = await axios.put(`/api/product/${productId}/status`, 
      { status: 3 },
      {
        headers: {
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json'
        }
      }
    );

    console.log(`[${currentTime}] [SUCCESS] [下架商品] 商品下架成功，商品ID: ${productId}`);
    applyFilter(); // 重新获取商品列表并保持筛选条件
  } catch (error: unknown) {
    const errorMessage = error instanceof Error ? error.message : '未知错误';
    console.error(`[${currentTime}] [ERROR] [下架商品] 商品下架失败，错误信息: ${errorMessage}`);
  }
};

/**
 * 编辑商品
 * @param productId 商品ID
 */
const editProduct = async (productId: number) => {
  console.log(`[${new Date().toLocaleString()}] [INFO] [编辑商品] 开始编辑商品，商品ID: ${productId}`);
  try {
    // 1. 获取商品详情
    const token = localStorage.getItem('token');
    const res = await axios.get(`/api/product/${productId}`, {
      headers: token ? { Authorization: `Bearer ${token}` } : {}
    });
    const product = res.data.product;
    console.log(`[${new Date().toLocaleString()}] [INFO] [编辑商品] 获取商品详情成功: ${JSON.stringify(product)}`);

    // 2. 填充表单数据
    title.value = product.title;
    description.value = product.description;
    price.value = product.price.toString();
    originalPrice.value = product.original_price ? product.original_price.toString() : '';
    category.value = product.category_id;

    // 3. 加载商品图片
    imageFiles.value = [];
    imageUrls.value = [];
    
    // 存储原始图片URL，用于后续删除操作比较
    originalImageUrls.value = [...(product.images || [])];

    // 处理原始图片
    if (product.images && product.images.length > 0) {
      console.log(`[${new Date().toLocaleString()}] [INFO] [编辑商品] 加载 ${product.images.length} 张原始图片`);
      for (let i = 0; i < product.images.length; i++) {
        const imageUrl = product.images[i];
        try {
          // 创建临时File对象用于预览
          const response = await fetch(getProductImageUrl(imageUrl));
          if (!response.ok) throw new Error(`图片加载失败: ${response.status}`);
          const blob = await response.blob();
          const fileName = imageUrl.split('/').pop() || 'image.jpg';
          const file = new File([blob], fileName, { type: blob.type }) as ExtendedFile;
          file.isOriginal = true;
          file.originalUrl = imageUrl;

          imageFiles.value.push(file);
          imageUrls.value.push(getProductImageUrl(imageUrl));
          console.log(`[${new Date().toLocaleString()}] [DEBUG] [编辑商品] 成功加载第 ${i+1}/${product.images.length} 张图片: ${imageUrl}`);
        } catch (error) {
          console.error(`[${new Date().toLocaleString()}] [ERROR] [编辑商品] 加载第 ${i+1}/${product.images.length} 张图片失败: ${imageUrl}, 错误: ${error instanceof Error ? error.message : '未知错误'}`);
          // 即使某张图片加载失败，继续处理其他图片
        }
      }
      console.log(`[${new Date().toLocaleString()}] [DEBUG] [编辑商品] 最终加载成功 ${imageFiles.value.length} 张图片`);
    }

    editingProductId.value = productId;
    showForm.value = true;
  } catch (error: any) {
    console.error(`[${new Date().toLocaleString()}] [ERROR] [编辑商品] 商品编辑失败: ${error?.message || '未知错误'}`);
    msg.value = '加载商品信息失败';
  }
};

const applyFilter = async () => {
  loading.value = true;
  try {
    const params: any = {
      page: currentPage.value,
      pageSize: pageSize.value
    };
    if (filterCategory.value) params.categoryId = filterCategory.value;
    if (filterKeyword.value) params.keyword = filterKeyword.value;
    if (filterMinPrice.value) params.min_price = filterMinPrice.value;
    if (filterMaxPrice.value) params.max_price = filterMaxPrice.value;
    if (filterCondition.value) params.condition = filterCondition.value;
    if (filterPriceOrder.value) params.price_order = filterPriceOrder.value;
    console.log(`[${new Date().toLocaleString()}] [INFO] 商品筛选请求参数: ${JSON.stringify(params)}`);
    const token = localStorage.getItem('token');
    const res = await axios.get('/api/product/filter', {
      params,
      headers: token ? { Authorization: `Bearer ${token}` } : {}
    });
    console.log(`[${new Date().toLocaleString()}] [INFO] 商品筛选响应: ${JSON.stringify(res.data)}`);
    products.value = res.data.products || [];
    totalPages.value = res.data.totalPages || 1;
    console.log(`[${new Date().toLocaleString()}] [INFO] 商品筛选成功: 数量=${products.value.length}, 总页数=${totalPages.value}`);
  } catch (err) {
    console.error(`[${new Date().toLocaleString()}] [ERROR] 商品筛选失败: ${err}`);
    products.value = [];
    totalPages.value = 1;
  }
  loading.value = false;
};
const getCategoryName = (id: any) => {
  const cat = allCategories.value.find((c: any) => c.category_id === id);
  return cat ? cat.name : '';
};

/**
 * 获取页码范围，用于显示分页按钮
 * @returns 页码数组
 */
const pageRange = computed(() => {
  const range = [];
  const maxVisiblePages = 5; // 最多显示5个页码按钮
  let startPage = Math.max(1, currentPage.value - Math.floor(maxVisiblePages / 2));
  let endPage = startPage + maxVisiblePages - 1;

  if (endPage > totalPages.value) {
    endPage = totalPages.value;
    startPage = Math.max(1, endPage - maxVisiblePages + 1);
  }

  for (let i = startPage; i <= endPage; i++) {
    range.push(i);
  }

  return range;
});

/**
 * 跳转到上一页
 */
const prevPage = () => {
  if (currentPage.value > 1) {
    currentPage.value--;
    applyFilter();
  }
};

/**
 * 跳转到下一页
 */
const nextPage = () => {
  if (currentPage.value < totalPages.value) {
    currentPage.value++;
    applyFilter();
  }
};

/**
 * 跳转到指定页码
 * @param page 目标页码
 */
const goToPage = (page: number) => {
  if (page !== currentPage.value && page >= 1 && page <= totalPages.value) {
    currentPage.value = page;
    applyFilter();
  }
};
</script>

<style scoped>
.product-page-layout {
  display: flex;
  min-height: 80vh;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.06);
  margin: 32px auto 0 auto;
  max-width: 1200px;
  overflow: hidden;
}
.product-sidebar {
  width: 220px;
  padding: 32px 18px 0 18px;
  background: #f8fafc;
  border-radius: 12px 0 0 12px;
}
.filter-form {
  display: flex;
  flex-direction: column;
  gap: 16px;
  margin-top: 18px;
}
.filter-row label {
  color: #475569;
  font-weight: 500;
  font-size: 14px;
}
.filter-row input,
.filter-row select {
  padding: 8px;
  border: 1px solid #e2e8f0;
  border-radius: 6px;
  font-size: 14px;
  width: 100%;
  box-sizing: border-box;
}

/* 表单行样式 */
.form-row {
  margin-bottom: 12px;
}

.form-row label {
  color: #334155;
  font-weight: 600;
  font-size: 14px;
  margin-bottom: 8px;
  display: block;
}

.form-row input,
.form-row select,
.form-row textarea {
  padding: 10px 12px;
  border: 1px solid #cbd5e1;
  border-radius: 8px;
  font-size: 14px;
  width: 100%;
  box-sizing: border-box;
  transition: all 0.2s ease;
  background-color: #fff;
}

.form-row input:focus,
.form-row select:focus,
.form-row textarea:focus {
  outline: none;
  border-color: #2563eb;
  box-shadow: 0 0 0 3px rgba(37, 99, 235, 0.1);
}

.form-row textarea {
  min-height: 100px;
  resize: vertical;
  padding: 12px;
}
.filter-row input[type="date"] {
  min-width: 120px;
  max-width: 100%;
  background: #fff;
  z-index: 2;
  position: relative;
}
.filter-row {
  position: relative;
  z-index: 1;
}
.filter-btn {
  margin-top: 10px;
  padding: 8px;
  background: #2563eb;
  color: #fff;
  border: none;
  border-radius: 6px;
  font-size: 14px;
  font-weight: 600;
  cursor: pointer;
  transition: background 0.2s;
}
.product-form {
  background-color: #fff;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
}

.submit-btn {
  padding: 10px 20px;
  background: #2563eb;
  color: #fff;
  border: none;
  border-radius: 8px;
  font-size: 14px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.2s ease;
  box-shadow: 0 2px 4px rgba(37, 99, 235, 0.2);
}

.submit-btn:hover {
  background: #1d4ed8;
  transform: translateY(-1px);
  box-shadow: 0 4px 6px rgba(37, 99, 235, 0.25);
}
.filter-btn:hover {
  background: #1d4ed8;
}
.product-main {
  flex: 1;
  padding: 32px 38px 0 38px;
  display: flex;
  flex-direction: column;
  background: #ffffff;
  border-radius: 0 12px 12px 0;
  box-shadow: 0 0 10px rgba(0,0,0,0.02);
}
.main-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 18px;
}

.main-header h1 {
  font-size: 24px;
  color: #1e293b;
  font-weight: 600;
}
.add-btn {
  padding: 8px 16px;
  background: #2563eb;
  color: #fff;
  border: none;
  border-radius: 6px;
  font-size: 14px;
  font-weight: 600;
  cursor: pointer;
  box-shadow: 0 2px 8px rgba(0,0,0,0.08);
  transition: background 0.2s;
}
.add-btn:hover {
  background: #1d4ed8;
}
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 1000;
  display: flex;
  justify-content: center;
  align-items: center;
}

.modal-content {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background-color: #fff;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
  width: 500px;
  max-width: 90%;
  z-index: 1001;
  overflow: hidden;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 24px;
  background-color: #f8fafc;
  border-bottom: 1px solid #e2e8f0;
  border-radius: 12px 12px 0 0;
}

.modal-header h2 {
  margin: 0;
  font-size: 18px;
  color: #1e293b;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #64748b;
  padding: 0 8px;
  transition: color 0.2s;
}

.close-btn:hover {
  color: #0f172a;
}

/* 分页样式 */
.pagination-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
  padding: 10px 0;
  border-top: 1px solid #e2e8f0;
}

.pagination-info {
  font-size: 14px;
  color: #64748b;
}

.pagination-buttons {
  display: flex;
  gap: 5px;
}

.pagination-btn {
  padding: 6px 12px;
  border: 1px solid #e2e8f0;
  border-radius: 6px;
  background-color: #ffffff;
  color: #475569;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.2s;
}

.pagination-btn:hover {
  background-color: #f8fafc;
  border-color: #cbd5e1;
}

.pagination-btn.active {
  background-color: #2563eb;
  color: #ffffff;
  border-color: #2563eb;
}

.pagination-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.modal-body {
  padding: 16px;
  max-height: 70vh;
  overflow-y: auto;
  -webkit-overflow-scrolling: touch;
}
.my-products-list {
  display: flex;
  flex-direction: column;
  gap: 18px;
}
.my-product-item {
  display: flex;
  align-items: center;
  gap: 18px;
  background: #f8fafc;
  border-radius: 8px;
  padding: 16px 18px;
  box-shadow: 0 1px 4px rgba(0,0,0,0.04);
}
.my-product-img {
  width: 64px;
  height: 64px;
  object-fit: cover;
  border-radius: 6px;
  border: 1.5px solid #e2e8f0;
}
.my-product-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 4px;
}
.my-product-title {
  font-weight: 600;
  font-size: 14px;
}
.my-product-desc {
  color: #666;
  font-size: 14px;
  margin-bottom: 2px;
}
.my-product-meta {
  display: flex;
  gap: 18px;
  font-size: 14px;
  color: #888;
}
.my-product-price {
  color: #2563eb;
  font-weight: 600;
}
/* 按钮样式已更新为btn-编辑和btn-删除 */
.cancel-btn {
  margin-left: 12px;
  padding: 8px;
  background: #e5e7eb;
  color: #333;
  border: none;
  border-radius: 6px;
  font-size: 14px;
  font-weight: 600;
  cursor: pointer;
  transition: background 0.2s;
}
.cancel-btn:hover {
  background: #cbd5e1;
}
.image-previews {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-top: 10px;
}

.preview-container {
  position: relative;
}

.image-preview {
  max-width: 150px;
  max-height: 150px;
  border-radius: 4px;
}

.remove-image-btn {
  position: absolute;
  top: 5px;
  right: 5px;
  background-color: rgba(255, 0, 0, 0.7);
  color: white;
  border: none;
  border-radius: 50%;
  width: 20px;
  height: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  font-size: 12px;
}
.status-tag {
  display: inline-block;
  padding: 4px 8px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
  margin-left: 8px;
}
.status-pending {
  background-color: #fef3c7;
  color: #d97706;
}
.status-active {
  background-color: #d1fae5;
  color: #059669;
}

/* 按钮通用样式 */
/* 上架按钮样式 */
.btn-上架 {
  border: none;
  cursor: pointer;
  transition: background 0.2s;
  padding: 5px 10px;
  border-radius: 4px;
  font-size: 13px;
  font-weight: 500;
  font-family: inherit;
  background-color: #d1fae5;
  color: #059669;
}

.btn-上架:hover {
  background-color: #a7f3d0;
}

/* 编辑按钮样式 */
.btn-编辑 {
  border: none;
  cursor: pointer;
  transition: background 0.2s;
  padding: 5px 10px;
  border-radius: 4px;
  font-size: 13px;
  font-weight: 500;
  font-family: inherit;
  background-color: #e0f2fe;
  color: #0369a1;
  margin-right: 8px;
}

.btn-编辑:hover {
  background-color: #bae6fd;
}

/* 下架按钮样式 */
.btn-删除 {
  border: none;
  cursor: pointer;
  transition: background 0.2s;
  padding: 5px 10px;
  border-radius: 4px;
  font-size: 13px;
  font-weight: 500;
  font-family: inherit;
  background-color: #fee2e2;
  color: #b91c1c;
}

.btn-删除:hover {
  background-color: #fecaca;
}
.status-sold {
  background-color: #e0e7ff;
  color: #4f46e5;
}
.status-offline {
  background-color: #f3f4f6;
  color: #6b7280;
}

.my-products-list {  
  display: flex;  
  flex-direction: column;  
  gap: 16px;  margin-top: 16px;
}
.my-product-item {  
  display: flex;  
  align-items: center;  
  gap: 16px;  
  background: #ffffff; 
  border-radius: 10px; 
  padding: 16px;  
  box-shadow: 0 2px 8px rgba(0,0,0,0.04);  
  transition: transform 0.2s, box-shadow 0.2s;
}
.my-product-item:hover {  
  transform: translateY(-2px);  
  box-shadow: 0 4px 12px rgba(0,0,0,0.06);
}
  .my-product-img {  
  width: 64px;  height: 64px;  
  object-fit: cover;  
  border-radius: 8px;  
  border: 1px solid #e2e8f0;
}
.my-product-info {  
  flex: 1;  display: flex;  
  flex-direction: column;  
  gap: 4px;
}
.my-product-title {  
  font-weight: 600;  
  font-size: 15px;  
  color: #1e293b;
}
.my-product-desc {  
  color: #64748b;  
  font-size: 13px;  
  display: -webkit-box;  
  -webkit-line-clamp: 1;  
  -webkit-box-orient: vertical;  
  overflow: hidden;
}
.my-product-meta {  
  display: flex;  
  flex-wrap: wrap;  
  gap: 12px;  
  font-size: 13px;  
  color: #64748b;  
  margin-top: 4px;
}
.my-product-price {  
  color: #2563eb;  
  font-weight: 600;
}
.my-product-actions {  
    display: flex;  gap: 8px;
}

.msg {
  color: #16a34a;
  margin-left: 10px;
}
.status-tag {
  margin-left: 8px;
  padding: 4px 8px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
  white-space: nowrap;
}
.status-sold {
  background: #f97316;
  color: white;
}
.status-offline {
  background: #ef4444;
  color: white;
}
</style>
